extends VBoxContainer

export(int) var number_position = 1
export(int) var value = 0
onready var label = $label
var next = null
var previous = null
var timer = 0

signal changed

# Called when the node enters the scene tree for the first time.
func _ready():
	pass # Replace with function body.


func _process(delta):
	if not has_focus(): 
		self.rect_scale = Vector2(1,1)
		return
	if Input.is_action_just_pressed("ui_up"):
		set_value(value+1)
	if Input.is_action_just_pressed("ui_down"):
		set_value(value-1)
	timer += delta
	var s = (sin(timer*5.0)*0.1) + 1.0
	self.rect_scale = Vector2(s,s)

func set_value(v, affect_next=true):
	if v > 9:
		if previous and affect_next:
			previous.set_value(previous.value+1, true)
		v = 0
	if v < 0: 
		if previous and affect_next:
			if previous.can_modify_previous():
				previous.set_value(previous.value-1, true)
		v = 9
	value = v
	label.text = str(v)
	if affect_next:
		emit_signal("changed")

func can_modify_previous():
	var is_valid = value > 0
	var prev = previous
	while prev:
		is_valid = is_valid or prev.value > 0
		prev = prev.previous
	return is_valid
